//
//
//

#include <iostream>
#include <enet/enet.h>

using namespace std;

ENetHost *client;

ENetAddress address;
ENetEvent event;
ENetPeer *peer;

int main(int argc, char **argv) {
	
	if (enet_initialize() != 0) {
		cerr << "Failed it initialize enet" << endl;
		return 1;
	}
	atexit(enet_deinitialize);
	
	// one outgoing connection with unrestricted bandwidth
	client = enet_host_create(NULL, 1, 0, 0);
	
	if (client == NULL) {
		cerr << "Failed to bind client" << endl;
		return 1;
	}
	
	// remote address
	enet_address_set_host(&address, "localhost");
	address.port = 4646;
	
	// connect to remote address allocating 2 channels
	peer = enet_host_connect(client, &address, 2);
	if (peer == NULL) {
		cout << "Could not connect to remote host" << endl;
		return 1;
	}
	
	// wait 5 seconds to connect 
	if (enet_host_service(client, &event, 5000) > 0 &&
		event.type == ENET_EVENT_TYPE_CONNECT)
	{
		cout << "Connected to remote host" << endl;
		
	} else {
		cerr << "Connection timed out" << endl;
		enet_peer_reset(peer);
		enet_host_destroy(client);
		return 1;
	}
	
	// try to send a packet of size 5
	ENetPacket *packet = 
		enet_packet_create("test", 5, ENET_PACKET_FLAG_RELIABLE);
	
	
	enet_peer_send(peer, 0, packet);
	enet_host_flush(client);
	
	// disconnect
	enet_peer_disconnect(peer, 0);
	while(enet_host_service(client, &event, 1000) &&
		event.type != ENET_EVENT_TYPE_DISCONNECT) 
	{
		// throw away any junk packets recieved
		if (event.type == ENET_EVENT_TYPE_RECEIVE) {
			enet_packet_destroy(event.packet);
		}
	}
	
	enet_host_destroy(client);
}
